/*
 * FunctionCallAst.cpp
 *
 *  Created on: 19 Nov 2010
 *      Author: kn308
 */
#include <sstream>
#include <MAlice/MAlice.h>
#include <MAlice/Codegen.h>

#include <MAlice/Ast/FunctionCallAst.h>
#include <MAlice/Ast/ListAst.h>

namespace MAlice
{

FunctionCallAst::FunctionCallAst(const string& name, ListAst* params) :
	mName(name), mParams(params)
{
}

FunctionCallAst::~FunctionCallAst()
{
}

llvm::Value* FunctionCallAst::generate()
{
	vector<Ast*> params = mParams->getChildren();
	vector<Value*> values;
	for (vector<Ast*>::iterator i = params.begin(); i != params.end(); i++)
	{
		if (Value* value = (*i)->generate())
		{
			values.push_back(value);
		} else
		{
			throw runtime_error("Cannot generate a function parameter in the call!");
		}
	}

	Codegen* g = Codegen::get();
	Builder* builder = g->getBuilder();
	if (Function* F = g->getModule()->getFunction(mName))
	{
		return builder->CreateCall(F, values.begin(), values.end(), "<call>");
	} else
	{
		stringstream ss;
		ss << "Function '" << mName << "' is not defined!";
		throw runtime_error(ss.str());
	}
}

}
